package com.danbay.framework.protocol.command.codec;

import com.danbay.framework.exception.MessageCodeException;
import com.danbay.framework.utils.JsonUtils;
import com.danbay.framework.utils.ReflectUtils;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Map;

/**
 * json数据解码
 * @author sjg
 *
 */
public class JsonDataDecoder implements ICmdDataDecoder {
	protected Log logger= LogFactory.getLog(getClass());
	private ObjectMapper objectMapper=new ObjectMapper();

	/**
	 * 将字符串解码成对象
	 */
	@SuppressWarnings("unchecked")
	@Override
	public <T> T decode(String data,Type dest) throws MessageCodeException {
		//无数据不解析json
		if(data==null || data.equals("")){
			return null;
		}

		try {
			//原始类型,直接返回解析结果
			if(!dest.getTypeName().contains(".") || dest.getTypeName().indexOf("java.lang.")==0){
				return new ObjectMapper().readValue(data, (Class<T>) dest);
			}
			//其它类型
			return JsonUtils.parse(objectMapper,data,dest);
		} catch (Exception e) {
			throw new MessageCodeException("json解析失败,错误码:1002",1002, e);
		}
	}

}
